import { debounce } from '@/utils/helper.js';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { ScrollView, View } from '@tarojs/components';
import { useRouter } from '@tarojs/taro';
import React, { useCallback, useEffect } from 'react';
import { connect } from 'react-redux';
import Imagelocation from '@/components/Imagelocation';

import ListEnd from '../giftCardDetail/listEnd';
import './index.scss';

const OrgLabelStatus = {
  shop: 1,
  takeAway: 2,
  all: 3,
};

const pageSize = 10;

const Store = ({ logo, name, orgLabelStatus }) => {
  return (
    <View className="store">
      <Imagelocation className="logo" src={logo} type="shop" />

      <View className="detail">
        <View className="org-name">{name}</View>
        <View className="tags">
          {[OrgLabelStatus.shop, OrgLabelStatus.all].includes(orgLabelStatus) && (
            <View className="store-tag shop-tag">
              <View className="tag-text">商城</View>
            </View>
          )}

          {[OrgLabelStatus.takeAway, OrgLabelStatus.all].includes(orgLabelStatus) && (
            <View className="store-tag take-away-tag">
              <View className="tag-text">外卖</View>
            </View>
          )}
        </View>
      </View>
    </View>
  );
};

const GiftCardStores = ({ dispatch, loading, giftCardStoreList, giftCardStoreFinished }) => {
  useShowLoading(loading, ['giftCard/fetchGiftCardStoreList']);

  const router = useRouter();
  const { params = {} } = router;

  // 获取礼品卡店铺列表
  const getNextList = useCallback(() => {
    return dispatch({
      type: 'giftCard/fetchGiftCardStoreList',
      payload: { pageSize, cardID: params.id },
    });
  }, [params.id]);

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !giftCardStoreFinished && giftCardStoreList?.length > 0 && getNextList();
  }, 1200);

  // 第一次获取礼品卡店铺列表
  useEffect(() => {
    getNextList();
  }, []);

  return (
    <>
      <ScrollView
        className="giftCardStores"
        enableFlex
        scrollY
        onScrollToLower={handleScrollToLower}
      >
        <View className="store-list">
          {giftCardStoreList?.map((store, index) => {
            return (
              <View key={store.id}>
                <Store {...store}></Store>
                {index === giftCardStoreList?.length - 1 ? null : (
                  <View className="store-split-line"></View>
                )}
              </View>
            );
          })}
        </View>

        {giftCardStoreFinished && giftCardStoreList?.length > 8 && <ListEnd />}
      </ScrollView>
    </>
  );
};
export default connect(({ loading, giftCard }) => ({
  loading,
  giftCardStoreList: giftCard.giftCardStoreList,
  giftCardStoreFinished: giftCard.giftCardStoreFinished,
}))(GiftCardStores);
